﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;


namespace PirateShare
{
    /// <summary>
    /// Interaction logic for FirstStartWindow.xaml
    /// </summary>
    public partial class FirstStartWindow : Window
    {
        public User CreatedUser = null;

        private RSACryptoServiceProvider RSAProvider;

        public FirstStartWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            btnRegenerate_Click(sender, e);
            txtDNS.Text = System.Net.Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString(); 
        }

        private void btnRegenerate_Click(object sender, RoutedEventArgs e)
        {
            RSAProvider = new RSACryptoServiceProvider();
            txtKey.Text = RSAProvider.ToXmlString(true);
        }

        private void btnAccept_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder whatsWrong = new StringBuilder();
            bool isFailed = false;


            ushort port;

            if (!UInt16.TryParse(txtPort.Text, out port))
            {
                whatsWrong.AppendLine("Port must be numeric!");
                isFailed = true;
            }
            else
            {
                if (port <= 200)
                {
                    whatsWrong.AppendLine("Port must be between 200 and 65535");
                    isFailed = true;
                }
            }

            txtNickname.Text = txtNickname.Text.Trim();

            Regex nickCheck = new Regex(@"^[a-zA-Z0-9_\-]+$");

            if (!nickCheck.IsMatch(txtNickname.Text))
            {
                whatsWrong.AppendLine("Nickname must contain only english characters and no spaces.");
                isFailed = true;
            }


            try
            {
                Dns.GetHostEntry(txtDNS.Text);
            }
            catch (Exception)
            {
                whatsWrong.AppendLine("Hostname / IP is incorrect or could not be resolved");
                isFailed = true;
            }

            if (isFailed)
            {
                MessageBox.Show(whatsWrong.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Hand);
            }
            else
            {
                this.CreatedUser = new User(txtNickname.Text, RSAProvider.ToXmlString(false), RSAProvider.ToXmlString(true), txtDNS.Text, (bool)chkUpnp.IsChecked);
                this.Close();
            }
        }
    }
}
